﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using SlamCms.Common;

namespace SlamCms.Web.Sitemaps
{
	public class MenuHtmlHelper : IHtmlString
	{
		private readonly SitemapHtmlHelper _sitemapHtmlHelper;
		private SitemapNode _startingNode;
		private int _maxDepth = int.MaxValue;
		private int _maxNodesPerLevel = int.MaxValue;
		private string _template;

		public MenuHtmlHelper(SitemapHtmlHelper sitemapHtmlHelper)
		{
			_sitemapHtmlHelper = sitemapHtmlHelper;
			_startingNode = sitemapHtmlHelper.CurrentNode;
		}

		public SitemapHtmlHelper Sitemap
		{
			get
			{
				return _sitemapHtmlHelper;
			}
		}

		public MenuHtmlHelper FromRoot()
		{
			_startingNode = _sitemapHtmlHelper.Sitemap.RootNode;
			return this;
		}

		public MenuHtmlHelper From(Predicate<SitemapNode> predicate)
		{
			Ensure.ArgumentNotNull(predicate, "predicate");
			_startingNode = _sitemapHtmlHelper.Sitemap.FindNode(predicate);
			return this;
		}

		public MenuHtmlHelper MaxNodesPerLevel(int maxNodesPerLevel)
		{
			Ensure.ArgumentNotOutOfRangeExclusive(maxNodesPerLevel, 1, int.MaxValue, "maxNodesPerLevel");
			_maxNodesPerLevel = maxNodesPerLevel;
			return this;
		}

		public MenuHtmlHelper MaxDepth(int depth)
		{
			Ensure.ArgumentNotOutOfRangeExclusive(depth, 1, int.MaxValue, "depth");
			_maxDepth = depth;
			return this;
		}

		public MenuHtmlHelper UseTemplate(string templateName)
		{
			_template = templateName;
			return this;
		}

		public string ToHtmlString()
		{
			var menuModel = new Menu(Sitemap, _startingNode, 1, _maxDepth, _template);
			menuModel.MaxNodesPerLevel = _maxNodesPerLevel;
			return _sitemapHtmlHelper.Html.HtmlHelperForModel(menuModel).DisplayForModel(_template ?? "Menu").ToHtmlString();
		}
	}
}
